import {isEmpty, resetState} from '@/utils/index';
import UserService from '@/services/user/index';
import {forwardLogin} from '@/utils/page'
import {Decrypt,Encrypt} from '@/utils/secret'


import sugarCallBack from '@/libs/sugar/callback/index';

let {judgeCallBack} = sugarCallBack;

const initState = {
    /**
     * 是否需要强制登录.
     * 监听是否强制登录，如果推送，socket，或者接口拦截器，将此值值true，将需要重新登录
     * 所以需要隔离成俩个状态
     */
    storeName:'userStore',
    forcedLogin: true,
    hasLogin: false,
    isRemeber:false,
    userData:{
        username:'',
        name: "",
        token:'',
        roleType:'0',
        avatarUrl:"/static/img/qq.png",
        message:[],
        badgeText:'',
        firstLogin:false,
		id:'',
        banSay:0
    },
    userDataForLogin:{
        username: undefined,
        password: undefined,
        devicNum: undefined,
        timestamp: undefined,
        gesture:undefined,
        useGesture:false
    },
    roleMenu:[
        // {
        //     icon:'/static/img/mine/list_icon-1.png',
        //     code:'assessmentReport',
        //     title:'评估报告',
        //     route:'/pages/tabbar/mine/analyze/index',
        //     role:['1']
        // },
        // {
        //     icon:'/static/img/mine/list_icon-2.png',
        //     code:'collect',
        //     title:'我的收藏',
        //     route:'/pages/tabbar/mine/collect/index',
        //     role:['1']
        // },
        // {
        //     icon:'/static/img/mine/list_icon-2.png',
        //     code:'push',
        //     title:'消息推送',
        //     route:'/pages/tabbar/mine/message/index',
        //     role:['1']
        // },
        // {
        //     icon:'/static/img/mine/list_icon-3.png',
        //     code:'analyseForTech',
        //     title:'评估报告',
        //     route:'/pages/tabbar/mine/analyze/teacher',
        //     role:['2']
        // }
    ],
};
const user = {
    namespaced: true,
    state: {
        ...initState,
        initState: () => initState,
        //service: new UserClient()
        service: new UserService(false)
    },
    mutations:{
        login(state,payload){
            const {callback,validUser,result,username} = payload;
            if(!validUser){
                judgeCallBack(callback,validUser);
                return;
            }
            const {customer,token} = result;
            const {name,userType,headUrl,id,firstLogin=false,banSay} = customer;

            state.userData.name = name || '未知用户';
			
            state.userData.username = Encrypt(username);
            state.userData.avatarUrl = headUrl || '/static/img/qq.png';
            state.userData.token = token;
            state.userData.roleType = userType;
			state.userData.id = id;
            state.userData.firstLogin = firstLogin;
			state.userData.banSay = banSay;

            state.hasLogin = true;
            state.forcedLogin = false;
            const {service,roleMenu,userDataForLogin,...user} = state;
            // uni.setStorage({
            //     key:'X-Access-Token',
            //     data:token
            // })
            uni.setStorage({
                key: 'user',
                data: user,
            });
			
            console.log('judgeCallBack')
            judgeCallBack(callback,validUser);
        },
        logout(state,payload){
            state.userData.username = "";
            state.hasLogin = false;
            state.forcedLogin = true;
            /*
             不可以进入存储
             */
            const {userDataForLogin} = state;
           // uni.removeStorage({key:'X-Access-Token'})
            uni.removeStorage({
                key: 'user',
            });
            uni.removeStorage({
                key: 'keepLoginData',
            });
            uni.removeStorage({
                key: 'tokenInfo',
            });
            //const {gesture,useGesture,...data} = userDataForLogin
            // uni.removeStorage({
            //     key: 'userDataForLogin',
            // });
            // uni.setStorage({
            //     key: 'userDataForLogin',
            //     data: {
            //         ...data,
            //         gesture:undefined,
            //         useGesture:false
            //     },
            // });
        },
        loadMessage(state,payload){
            const {last,data,page} = payload;
            if (page==0){
                state.userData.message = data;
            }else {
                state.userData.message = [...state.userData.message,...data];
            }
        },
        updateBadge(state,payload){
            const {badgeText} = payload;
            console.log('badgeText:',badgeText)
            state.userData.badgeText = badgeText;
            const {service,roleMenu,...user} = state;
            uni.setStorage({
                key: 'user',
                data: user,
            });
        },
        restoreDataFromStorage(state,payload){
            const {data,userDataForLogin} = payload;
            if(data!=undefined){
                Object.assign(state,data);
                return;
            }   
            if(userDataForLogin!=undefined){
                Object.assign(state.userDataForLogin,userDataForLogin);
                return;
            }            
        },
        enableUseGesture(state,payload){
            const {useGesture,callback} = payload;
           
            state.userDataForLogin.useGesture = useGesture;
            if(!useGesture){
                state.userDataForLogin.gesture = undefined;
            }
            // else{
            //     if(!state.userDataForLogin.gesture){
            //         state.userDataForLogin.gesture = '123456'
            //     }
            // }
            uni.setStorage({
                key:'userDataForLogin',
                data:state.userDataForLogin
            });
            judgeCallBack(callback);
        },
        setUserDataForLogin(state,payload){
            const {password,devicNum,gesture,callback} = payload;
			const username =Encrypt(payload.username);
            if(!isEmpty(gesture)){
                state.userDataForLogin.gesture = gesture;
            }else if(!isEmpty(password)){
                state.userDataForLogin.password =  Encrypt(password);
            }
			
            Object.assign(state.userDataForLogin,{username,devicNum,timestamp: new Date().getTime()});
            uni.setStorage({
                key:'userDataForLogin',
                data:state.userDataForLogin
            });
            judgeCallBack(callback);
        },
        updateAvatar(state,payload){
            const {avatarUrl} = payload;
            console.log('avatarUrl:',avatarUrl)
            state.userData.avatarUrl = avatarUrl;
            const {service,roleMenu,...user} = state;
            uni.setStorage({
                key: 'user',
                data: user,
            });
        }
    },
    actions: {
        async enableUseGesture({ dispatch,commit, state }, payload={}){
            const {callback,...params} = payload;
            /*
            向服务器端发起保存手势或者密码接口
            */
        //    const resultDto = await state.service.modifyPwd(params);
        //    if(resultDto.success){
        //        commit('setUserDataForLogin',payload);
        //    }

           commit('enableUseGesture',payload);
        },
        async setUserDataForLogin({ dispatch,commit, state }, payload={}){
            const {callback,...params} = payload;
            /*
            向服务器端发起保存手势或者密码接口
            */
        //    const resultDto = await state.service.modifyPwd(params);
        //    if(resultDto.success){
        //        commit('setUserDataForLogin',payload);
        //    }
            commit('setUserDataForLogin',payload);
           
        },
        async restoreDataFromStorage({ dispatch,commit, state }, payload={}){
            uni.getStorage({
                key: 'user',
                success:function({data}){
                    console.log('data:',data)
                    if (data!=undefined && data!=''){
                        /*
                        还原用户状态
                         */
                        //state = {...state,...localUser};
                        //const {forcedLogin,hasLogin,isRemeber,userData} = localUser;
                        //Object.assign(state,data);
                        commit('restoreDataFromStorage',{data})
                    }
                }
            });
            uni.getStorage({
                key: 'userDataForLogin',
                success:function({data:userDataForLogin}){
                    console.log('userDataForLogin:',userDataForLogin)
                    if (userDataForLogin!=undefined && userDataForLogin!=''){
                        /*
                        还原用户状态
                         */
                        //state = {...state,...localUser};
                        //const {forcedLogin,hasLogin,isRemeber,userData} = localUser;
                        //Object.assign(state,{userDataForLogin});
                        commit('restoreDataFromStorage',{userDataForLogin})
                    }
                }
            })  
        },
        async login({ dispatch,commit, state }, payload={}) {
            let {callback,...loginInfo} = payload;
            console.log('loginInfo:',loginInfo)
            const {gesture,option} = loginInfo;
            if(option=='gesture'){
                /*
                先做手势验证
                */
               if(gesture!=state.userDataForLogin.gesture){
                payload.validUser = false
                commit('login',payload)
                return;
               }
               /*
               本地设备密码验证通过，讲保存的密码加入请求
               */
              loginInfo.gesture = Decrypt(state.userDataForLogin.password);
            }
            const resultDto = await state.service.login(loginInfo);
            let validUser = resultDto.success;
            console.log('resultDto:',resultDto)
            if (validUser){
                const result = resultDto.result;
                const {username} = loginInfo;
                commit('login',{
                    ...payload,result,validUser,username
                })
            }
        },
        async logout({ dispatch,commit, state }, payload={}) {
            /*
            往远程发出注销操作
             */
            commit('logout');
            forwardLogin();
            
        },
        async loadMessage({ dispatch,commit, state }, payload={}){
            /*
            加载远程消息
             */
            commit('loadMessage',payload);
        }
    },
    getters: {
        getUser: state=>{
            const {service,...user} = state;
            // console.log('state.hasLogin:',state.hasLogin)
            // if (state.hasLogin) return user;
            // if (!isEmpty(localUser)){
            //     /*
            //     还原用户状态
            //      */
            //     state = {...state,...localUser};
            // }
            return user;
        }
    },
    modules: {}
};
export default user;